﻿using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iTool.SQL.Analysis.WhereClause
{
    public class SqlComparisonBooleanExpressionAnalysis : SqlAnalysisBase
    {
        public SqlComparisonBooleanExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            //StringBuilder where = base.GetWhereBuilder();
            var expression = (SqlComparisonBooleanExpression)base.CodeObject;

            var groupWheres = base.GetGroupWhere();
            WhereOptions whereOptions = new WhereOptions();
            SubWhereOptions sub = null;
            whereOptions.Parent = base.WhereOptions;

            if (base.WhereOptions is GroupWhereOptions group)
            {
                group.Wheres.Add(whereOptions);
            }
            else if (base.WhereOptions is SubWhereOptions)
            {
                sub = (SubWhereOptions)base.WhereOptions;
                // sub.Wheres[^1] is group
                if (sub.Wheres.Count == 0)
                {
                    sub.Wheres.Add(new GroupWhereOptions());
                }
                sub.Wheres[^1].Wheres.Add(whereOptions);
            }
            else
            {
                groupWheres[^1].Wheres.Add(whereOptions);
            }



            base.Next(beforeAction:(index,_, _1) => {
                if (index == 1)
                {
                    whereOptions.ComparisonBooleanExpressionType =
                    (ComparisonBooleanExpressionType)Enum.Parse(
                        typeof(ComparisonBooleanExpressionType),
                        expression.ComparisonOperator.ToString());

                    //where.Append($" {expression.ComparisonOperator}{(_ is SqlLiteralExpression ? " " : String.Empty)}");
                }
                return true;
            },whereOptions: whereOptions);

            if (sub != null)
            {
                base.WhereOptions = sub.Wheres[^1];
            }
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
